package com.kedou.fragment;

import java.io.ByteArrayOutputStream;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.baidu.cyberplayer.core.BVideoView;
import com.baidu.cyberplayer.core.BVideoView.OnCompletionListener;
import com.baidu.cyberplayer.core.BVideoView.OnErrorListener;
import com.baidu.cyberplayer.core.BVideoView.OnPreparedListener;
import com.basv.gifmoviewview.widget.GifMovieView;
import com.kedou.app.Config;
import com.kedou.app.ProjectDetailActivity.ToFragment;
import com.kedou.app.R;
import com.kedou.domain.ProjectItem;
import com.kedou.util.DensityUtil;
import com.kedou.util.NetworkUtil;
import com.kedou.util.OrientationHelper;
import com.kedou.util.Screen;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Picasso.LoadedFrom;
import com.squareup.picasso.Target;

/**
 * 项目介绍的Fragment
 * 
 * @author zhouchao
 * 
 */
public class ProjectIntroductionFragment extends Fragment implements
		OnClickListener, OnPreparedListener, OnCompletionListener,
		OnErrorListener, OnTouchListener, Target, ToFragment {
	private Context mContext;
	private ProjectItem mProjectItem;
	private ImageView mDetailImageView;
	private ImageButton mPrePlayButton;
	private GifMovieView mLoadingGif;
	private int mCurrentScape;
	private SharedPreferences mSharedPreferences;
	private View mVideoAction;
	private OrientationEventListener mOrientationEventListener;
	private Bitmap mDetailPicture;
	private RelativeLayout mHeaderWrapper;
	private Button mZoomButton;
	private int mLastPos = 0;
	private final int UI_EVENT_UPDATE_CURRPOSITION = 1;
	private BVideoView mVV = null;
	private RelativeLayout mViewHolder = null;
	private RelativeLayout mController = null;
	private SeekBar mProgress = null;
	private TextView mDuration = null;
	private TextView mCurPosition = null;
	private Button mPlayBtn = null;
	private Activity activity;
	/**
	 * 已支付金额
	 */
	private TextView mTvHavePaid;

	/**
	 * 众筹目标
	 */
	private TextView mTvGoal;

	/**
	 * 占项目股权
	 */
	private TextView mTvPercentOfProject;

	/**
	 * 关注数
	 */
	private TextView mTvAttentionAmount;

	/**
	 * 认筹状态
	 */
	private TextView mTvRenchouState;
	private WebView mWebview;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mContext = activity;
		this.activity = activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null
				&& savedInstanceState.containsKey("Animation")) {
			mLastPos = savedInstanceState.getInt("LastPosition");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_projectintroduction,
				null);
		initData();
		initView(view);
		setText();
		play();
		return view;
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			mProjectItem = bundle.getParcelable("project_item");
		}
	}

	/**
	 * 初始化布局
	 */
	private void initView(View view) {
		mDetailImageView = (ImageView) view.findViewById(R.id.detailPic);
		mVideoAction = view.findViewById(R.id.VideoAction);
		mPrePlayButton = (ImageButton) view.findViewById(R.id.pre_play_button);
		mLoadingGif = (GifMovieView) view.findViewById(R.id.loading_gif);
		mPlayBtn = (Button) view.findViewById(R.id.play_btn);
		mProgress = (SeekBar) view.findViewById(R.id.media_progress);
		mDuration = (TextView) view.findViewById(R.id.time_total);
		mCurPosition = (TextView) view.findViewById(R.id.time_current);
		mController = (RelativeLayout) view.findViewById(R.id.controlbar);
		mViewHolder = (RelativeLayout) view.findViewById(R.id.view_holder);
		mVV = (BVideoView) view.findViewById(R.id.video_view);
		mHeaderWrapper = (RelativeLayout) view
				.findViewById(R.id.header_wrapper);
		mZoomButton = (Button) view.findViewById(R.id.zoom_btn);
		mTvHavePaid = (TextView) view.findViewById(R.id.tv_have_paid);
		mTvGoal = (TextView) view.findViewById(R.id.tv_goal);
		mTvPercentOfProject = (TextView) view
				.findViewById(R.id.tv_percent_of_project);
		mTvAttentionAmount = (TextView) view
				.findViewById(R.id.tv_attention_amount);
		mTvRenchouState = (TextView) view.findViewById(R.id.tv_renchou_state);
		mWebview = (WebView) view.findViewById(R.id.webview);
	}

	/**
	 * 设置文本
	 */
	private void setText() {
		mTvHavePaid.setText(mProjectItem.getPaid());
		mTvGoal.setText(mProjectItem.getGoal());
		mTvPercentOfProject.setText(mProjectItem.getAccounting());
		mTvAttentionAmount.setText(mProjectItem.getFollowNum());
		switch (mProjectItem.getProjectStatus()) {
		case 0:
			mTvRenchouState.setText(getResources().getString(
					R.string.renchou_state_zero));
			break;

		case 1:
			mTvRenchouState.setText(getResources().getString(
					R.string.renchou_state_one));
			break;
		case 2:
			mTvRenchouState.setText(getResources().getString(
					R.string.renchou_state_two));
			break;
		case 3:
			mTvRenchouState.setText(getResources().getString(
					R.string.renchou_state_three));
			break;
		}
		WebSettings settings = mWebview.getSettings();
		settings.setJavaScriptEnabled(true);
		mWebview.setInitialScale(100);// 初始显示比例100%
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		mWebview.setWebViewClient(new MyWebViewClient());
		// mWebview.setWebChromeClient(new WebViewClient());
		// TODO 修改url
		mWebview.loadUrl("http://www.taobao.com");
	}

	/**
	 * 自己处理url，禁止调用第三方浏览器
	 * 
	 * @author zhouchao
	 * 
	 */
	class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url_) {
			view.loadUrl(url_);
			return true;
		}
	}

	/**
	 * 播放相关
	 */
	private void play() {
		mSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(mContext);
		mCurrentScape = OrientationHelper.PORTRAIT;
		initPlayer();
		initContent();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.pre_play_button:
			startPlayAnimation(mLastPos);
			break;
		case R.id.play_btn:
			if (mVV.isPlaying()) {
				mPlayBtn.setBackgroundResource(R.drawable.play_btn_style);
				mVV.pause();
			} else {
				mPlayBtn.setBackgroundResource(R.drawable.pause_btn_style);
				mVV.resume();
			}
			mController.setVisibility(View.INVISIBLE);
			break;
		case R.id.zoom_btn:
			if (mCurrentScape == OrientationHelper.LANDSCAPE) {
				setMinSize();
			} else {
				setMaxSize();
			}
			break;
		default:
			break;
		}

	}

	/**
	 * 播放视频
	 * 
	 * @param start
	 * @param animation
	 */
	private void startPlayAnimation(final int start) {
		final String playUrl = "http://giftsoninternet.com/android/EngageApp/VuforiaSizzleReel_1.m4v";
		startPlayAnimationFromNet(playUrl, mLastPos);
	}

	/**
	 * 播放网络视频
	 * 
	 * @param url
	 * @param start
	 * @param animation
	 */
	private void startPlayAnimationFromNet(final String url, final int start) {
		if (NetworkUtil.isNetworkAvailable(mContext)) {
			if (NetworkUtil.isWifiConnected(mContext)) {
				mPrePlayButton.setVisibility(View.INVISIBLE);
				mVideoAction.setVisibility(View.INVISIBLE);
				mVV.setVideoPath(url);
				mVV.seekTo(start);
				mVV.start();
				mPlayBtn.setBackgroundResource(R.drawable.pause_btn_style);
				hideControls();
				activity.getWindow().addFlags(
						WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			} else {
				new AlertDialog.Builder(mContext)
						.setTitle(R.string.tip)
						.setMessage(R.string.no_wifi_force_play)
						.setPositiveButton(R.string.yes,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										mPrePlayButton
												.setVisibility(View.INVISIBLE);
										mVideoAction
												.setVisibility(View.INVISIBLE);
										mVV.setVideoPath(url);
										mVV.seekTo(start);
										mVV.start();
										mPlayBtn.setBackgroundResource(R.drawable.pause_btn_style);
										hideControls();
										activity.getWindow()
												.addFlags(
														WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
									}
								}).setNegativeButton(R.string.no, null)
						.create().show();
			}
		} else {
			Toast.makeText(mContext, R.string.no_network, Toast.LENGTH_LONG)
					.show();
		}
	}

	@Override
	public void onBitmapFailed() {
		mLoadingGif.setVisibility(View.INVISIBLE);
		mPrePlayButton.setVisibility(View.VISIBLE);
		mVideoAction.setVisibility(View.VISIBLE);
	}

	@Override
	public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) {
		mDetailImageView.setImageBitmap(bitmap);
		mDetailPicture = bitmap;
		mLoadingGif.setVisibility(View.INVISIBLE);
		mPrePlayButton.setVisibility(View.VISIBLE);
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		mDetailPicture.compress(CompressFormat.JPEG, 100, bytes);
	}

	@SuppressLint("HandlerLeak")
	Handler mUIHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UI_EVENT_UPDATE_CURRPOSITION:
				int currPosition = mVV.getCurrentPosition();
				int duration = mVV.getDuration();
				updateTextViewWithTimeFormat(mCurPosition, currPosition);
				updateTextViewWithTimeFormat(mDuration, duration);
				mProgress.setMax(duration);
				mProgress.setProgress(currPosition);
				mUIHandler.sendEmptyMessageDelayed(
						UI_EVENT_UPDATE_CURRPOSITION, 200);
				break;
			default:
				break;
			}
		}
	};

	private void updateTextViewWithTimeFormat(TextView view, int second) {
		int hh = second / 3600;
		int mm = second % 3600 / 60;
		int ss = second % 60;
		String strTemp = null;
		if (0 != hh) {
			strTemp = String.format(Locale.CHINA, "%02d:%02d:%02d", hh, mm, ss);
		} else {
			strTemp = String.format(Locale.CHINA, "%02d:%02d", mm, ss);
		}
		view.setText(strTemp);
	}

	private Timer mt;

	public void touchControlBar() {
		if (mController.getVisibility() == View.INVISIBLE) {
			mController.setVisibility(View.VISIBLE);
			mt = new Timer();
			mt.schedule(new TimerTask() {
				@Override
				public void run() {
					activity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mController.setVisibility(View.INVISIBLE);
						}
					});
				}
			}, 6000);
		} else {
			if (mt != null) {
				mt.cancel();
			}
			mController.setVisibility(View.INVISIBLE);
		}
	}

	public void hideControls() {
		mController.setVisibility(View.INVISIBLE);
	}

	/**
	 * 初始化播放器
	 */
	private void initPlayer() {
		BVideoView.setAKSK(Config.BAIDU_AK, Config.BAIDU_SK);
		mZoomButton.setOnClickListener(this);
		mVV.setVideoScalingMode(BVideoView.VIDEO_SCALING_MODE_SCALE_TO_FIT);
		mPlayBtn.setOnClickListener(this);
		mVV.setOnPreparedListener(this);
		mVV.setOnCompletionListener(this);
		mVV.setOnErrorListener(this);
		registerCallbackForControls();
	}

	/**
	 * 初始化内容
	 */
	private void initContent() {
		mPrePlayButton.setOnClickListener(this);
		mViewHolder.setOnTouchListener(this);
		Picasso.with(mContext)
				.load("http://apppic.animetaste.org/upload/2014/06/191821_betfairthisisplay1.JPG")
				.placeholder(R.drawable.big_bg).into(this);
	}

	private Handler toastHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Toast.makeText(mContext, R.string.play_offline, Toast.LENGTH_SHORT)
					.show();
		}
	};

	/**
	 * 停止播放
	 */
	private void stopPlay() {
		if (mVV.isPlaying() == false)
			return;
		mLastPos = mVV.getCurrentPosition();
		mVV.stopPlayback();
		activity.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	/**
	 * 暂停播放
	 */
	private void pausePlay() {
		if (mVV.isPlaying() == false)
			return;
		mLastPos = mVV.getCurrentPosition();
		mVV.pause();
		activity.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
	}

	/**
	 * 全屏
	 */
	@SuppressLint("InlinedApi")
	private void setMaxSize() {
		activity.findViewById(R.id.title_projectdetail)
				.setVisibility(View.GONE);
		activity.findViewById(R.id.ll_lanmu).setVisibility(View.GONE);
		activity.findViewById(R.id.ll_bottom).setVisibility(View.GONE);
		if (Build.VERSION.SDK_INT >= 9) {
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		} else {
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		activity.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
				Screen.getScreenWidth(activity.getWindowManager()),
				Screen.getScreenHeight(activity.getWindowManager()));
		mHeaderWrapper.setLayoutParams(param);
		mVV.setLayoutParams(param);
		mZoomButton.setBackgroundResource(R.drawable.screensize_zoomin_button);
		mCurrentScape = OrientationHelper.LANDSCAPE;
	}

	/**
	 * 取消全屏
	 */
	private void setMinSize() {
		activity.findViewById(R.id.title_projectdetail).setVisibility(
				View.VISIBLE);
		activity.findViewById(R.id.ll_lanmu).setVisibility(View.VISIBLE);
		activity.findViewById(R.id.ll_bottom).setVisibility(View.VISIBLE);
		activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		activity.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		System.out.println((Activity) mContext);
		RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
				Screen.getScreenWidth(((Activity) mContext).getWindowManager()),
				DensityUtil.dp2px(activity, 225));
		mHeaderWrapper.setLayoutParams(param);
		mVV.setLayoutParams(param);
		mZoomButton.setBackgroundResource(R.drawable.screensize_zoomout_button);
		mCurrentScape = OrientationHelper.PORTRAIT;
	}

	private void registerCallbackForControls() {

		OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				updateTextViewWithTimeFormat(mCurPosition, progress);
			}

			public void onStartTrackingTouch(SeekBar seekBar) {
				mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION);
			}

			public void onStopTrackingTouch(SeekBar seekBar) {
				int seekPosition = seekBar.getProgress();
				mVV.seekTo(seekPosition);
				mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION);
			}
		};
		mProgress.setOnSeekBarChangeListener(seekBarChangeListener);
	}

	@Override
	public boolean onError(int arg0, int arg1) {
		errorHandler.sendEmptyMessage(0);
		return true;
	}

	private Handler errorHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			setMinSize();
			mPrePlayButton.setVisibility(View.VISIBLE);
			mVideoAction.setVisibility(View.VISIBLE);
			mDetailImageView.setVisibility(View.VISIBLE);
			Toast.makeText(mContext, R.string.play_error, Toast.LENGTH_SHORT)
					.show();
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mCompleteHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			mPrePlayButton.setVisibility(View.VISIBLE);
			mVideoAction.setVisibility(View.VISIBLE);
		}

		;
	};

	@Override
	public void onCompletion() {
		mCompleteHandler.sendEmptyMessage(0);
		mLastPos = 0;
		int playCount = mSharedPreferences.getInt("playCount", 0);
		mSharedPreferences.edit().putInt("playCount", playCount + 1).commit();
		// if (mCurrentScape == OrientationHelper.LANDSCAPE) {
		//
		// activity.runOnUiThread(new Runnable() {
		//
		// @Override
		// public void run() {
		// setMinSize();
		// }
		// });
		//
		// }
		// ;

	}

	@Override
	public void onResume() {
		super.onResume();
		if (mLastPos != 0) {
			startPlayAnimation(mLastPos);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		pausePlay();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopPlay();
		if (mOrientationEventListener != null)
			mOrientationEventListener.disable();
	}

	@Override
	public void onPrepared() {
		mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		touchControlBar();
		return false;
	}

	//
	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// if (mCurrentScape == OrientationHelper.LANDSCAPE) {
	// setMinSize();
	// return true;
	// }
	// }
	// return super.onKeyDown(keyCode, event);
	// }

	@Override
	public void passValue() {
		int num = Integer.valueOf(mTvAttentionAmount.getText().toString());
		num = num + 1;
		mTvAttentionAmount.setText(String.valueOf(num));
	}

	@Override
	public void cancelAttention() {
		int num = Integer.valueOf(mTvAttentionAmount.getText().toString());
		num = num - 1;
		mTvAttentionAmount.setText(String.valueOf(num));
	}

}
